/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年4月28日    li.shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.gateway.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @FileName InputStreamCacher.java
 * @Description: 缓存InputStream，以便InputStream的重复利用
 *
 * @Date 2017年4月28日 下午2:08:24
 * @author li.shangzhi
 * @version 1.0
 */
public class InputStreamCacher {

	private static final Logger logger = LoggerFactory.getLogger(InputStreamCacher.class);

	/**
	 * 将InputStream中的字节保存到ByteArrayOutputStream中。
	 */
	private ByteArrayOutputStream byteArrayOutputStream = null;

	public InputStreamCacher(InputStream inputStream) {
		if (null == inputStream)
			return;
		byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(buffer)) > -1) {
				byteArrayOutputStream.write(buffer, 0, len);
			}
			byteArrayOutputStream.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public InputStream getInputStream() {
		if (null == byteArrayOutputStream)
			return null;
		return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
	}

	public void close() {
		if (null != byteArrayOutputStream) {
			try {
				byteArrayOutputStream.close();
			} catch (IOException e) {
				logger.error("关闭输入流缓存出错");
			}
		}
	}

}
